<script setup lang="ts">
  import { PropType, ref, watch } from 'vue'
  import orderService from './service'
  import Filter from '../../../../../views/order/list/components/Filter.vue'
  import { GetOrderListParam } from '../../../../../views/order/list/types'
  import HButton from '../../../../common/button/HButton.vue'
  import HModal from '../../../../common/Modal/HModal.vue'
  import HLink from '../../../../common/link/HLink.vue'

  const props = defineProps({
    exportFilter: {
      type: Object as PropType<GetOrderListParam>,
      required: true,
    },
    modalVisible: {
      type: Boolean,
      default: () => false,
    },
    getFilterDate: {
      type: Object,
      default:() => ({})
    },
  })

  const emits = defineEmits<{
    (e: 'close', value: boolean): void
  }>()

  const {
    exportFieldList,
    customFieldList,
    sysExportFieldList,
    orderSettlementField,
    getOrderSettlementFieldExportFun,
    addOrderSettlementField,
    getOrderCustomFieldList,
    getOrderExportFieldList,
    getOrderSysExportFieldList,
    addAllToExportFields,
    addSysFieldToExportFields,
    addCustomFieldToExportFields,
    removeAllExportField,
    removeFromExportFields,
    saveExportFieldList,
    saveAndExportFieldList,
  } = orderService

  // 字段导出的筛选组件实例
  const exportFieldFilterRef = ref<InstanceType<typeof Filter> | null>(null)

  // 弹窗状态
  const visible = ref(false)

  // 保存字段
  const onSaveExportField = () => {
    if (exportFieldFilterRef.value) {
      const filter = exportFieldFilterRef.value.getFilter()
      if (filter) {
        saveExportFieldList()
      }
    }
  }

  // 拖拽的元素的索引
  const moveIndex = ref(-1)

  // 目标位置
  const targetIndex = ref(-1)

  // 拖拽开始事件
  const handleDragStart = (index: number) => {
    moveIndex.value = index
  }

  // 拖拽结束事件
  const handleDragEnd = () => {
    const moveItem = exportFieldList.value[moveIndex.value]
    const targetItem = exportFieldList.value[targetIndex.value]
    exportFieldList.value.splice(moveIndex.value, 1, targetItem)
    exportFieldList.value.splice(targetIndex.value, 1, moveItem)
  }

  // 当拖动的元素进入到当前元素时触发
  const handleDragEnter = (index: number) => {
    targetIndex.value = index
  }

  
    // 保存并导出
    const handleSaveAndExportField = () => {
    if (props.getFilterDate) {
      saveAndExportFieldList(props.getFilterDate)
    }
  }

  // // 保存并导出
  // const handleSaveAndExportField = () => {
  //   let result: GetOrderListParam | null = null

  //   if (exportFieldFilterRef.value) {
  //     const filter = exportFieldFilterRef.value.getFilter()
  //     console.log(filter.addresses,"addresses");  // 这里能打印是因为Filter组件内部可能有addresses属性
      
  //     result = Object.assign(props.exportFilter, {
  //       dateFieldType: filter.dateFieldType, // 时间字段类型：1-报单日期，2-完工日期，3-结算日期
  //       dateType: filter.dateType, //报单时间类型
  //       fieldId: filter.fieldId, //工单字段名
  //       fieldSearch: filter.fieldSearch, //工单字段搜索关键词
  //       orderEndTime: filter.orderEndTime, //报单结束时间
  //       orderNo: filter.orderNo, //工单单号
  //       orderStartTime: filter.orderStartTime, //报单开始时间
  //       goodsSearch: filter.goodsSearch, //	商品搜索：品牌/产品名称/产品型号
  //       orderUserSearch: filter.orderUserSearch, // 工单客户搜索关键词：客户名称/客户手机号/客户地址
  //       addresses: filter.addresses, // 地址
  //     })
  //     console.log("result", result);
      
      
  //   }

  //   if (result) {
  //     saveAndExportFieldList(result)
  //   }
  // }

  // 导出工单数据
  const getOrderExportField = async () => {
    await getOrderExportFieldList()
    await getOrderSysExportFieldList()
    await getOrderCustomFieldList()
    await getOrderSettlementFieldExportFun()
    exportFieldList.value.forEach((column) => {
      if (column.type === 1) {
        const index = sysExportFieldList.value.findIndex((item) => item.code === column.value)
        sysExportFieldList.value.splice(index, 1)
      } else if (column.type === 2) {
        const index = customFieldList.value.findIndex((item) => item.id === column.value)
        customFieldList.value.splice(index, 1)
      } else if (column.type === 3) {
        const index = orderSettlementField.value.findIndex((item) => item.value === column.value)
        orderSettlementField.value.splice(index, 1)
      }
    })

    visible.value = true
  }

  // 关闭弹窗事件
  const onClose = () => {
    visible.value = false
    emits('close', false)
  }

  watch(
    () => props.modalVisible,
    (value) => {
      if (value) {
        getOrderExportField()
      }
    },
    { immediate: true },
  )
</script>

<template>
  <div>
    <HModal v-model="visible" title="工单导出" @close="onClose" :width="1000">
      <div class="modal_content">
        <!-- 条件搜索 -->
        <!-- <div class="filter_container">
          <div>条件搜索</div>
          <Filter ref="exportFieldFilterRef" />
        </div> -->

        <!-- 导出字段 -->
        <div class="export_field_container">
          <el-space>
            <div class="title">导出字段</div>
            <div class="sub_title">（拖拽可排序）</div>
            <HLink type="error" @click="removeAllExportField">清空全部</HLink>
          </el-space>
          <div style="max-height: 220px; overflow: auto; width: 98%; padding-top: 6px">
            <el-space wrap :size="10">
              <div
                v-for="(field, index) in exportFieldList"
                :key="field.value"
                :draggable="true"
                @dragstart="handleDragStart(index)"
                @dragend="handleDragEnd"
                @dragenter="handleDragEnter(index)"
                @mouseenter="() => (field.showClose = true)"
                @mouseleave="() => (field.showClose = false)"
                class="export-field-item"
                @click="removeFromExportFields(field)"
              >
                <div class="export-field-item-text">{{ field.name }}</div>
                <div class="export-field-item-btn">-</div>
              </div>
            </el-space>
          </div>
        </div>

        <!-- 系统字段 -->
        <div class="system_field_container">
          <el-space>
            <div class="title">系统字段</div>
            <div class="sub_title">（点击添加）</div>
            <HLink type="error" @click="addAllToExportFields(1)">添加全部</HLink>
          </el-space>
          <el-space wrap :size="10">
            <div
              :key="field.id"
              @mouseenter="() => (field.showAdd = true)"
              @mouseleave="() => (field.showAdd = false)"
              v-for="field in sysExportFieldList"
              class="add-field-item"
              @click="addSysFieldToExportFields(field)"
            >
              <div class="add-field-item-text">{{ field.name }}</div>
              <div class="add-field-item-btn">+</div>
            </div>
          </el-space>
        </div>

        <!-- 自定义字段 -->
        <div class="custom_field_container">
          <el-space>
            <div class="title">工单自定义字段</div>
            <div class="sub_title">（点击添加）</div>
            <HLink type="error" @click="addAllToExportFields(2)">添加全部</HLink>
          </el-space>
          <el-space wrap :size="10">
            <div
              :key="column.id"
              v-for="column in customFieldList"
              @mouseenter="() => (column.showAdd = true)"
              @mouseleave="() => (column.showAdd = false)"
              class="add-field-item"
              @click="addCustomFieldToExportFields(column)"
            >
              <div class="add-field-item-text">{{ column.name }}</div>
              <div class="add-field-item-btn">+</div>
            </div>
          </el-space>
        </div>
        <!-- 结单字段 -->
        <div class="custom_field_container">
          <el-space>
            <div class="title">结单字段</div>
            <div class="sub_title">（点击添加）</div>
            <HLink type="error" @click="addAllToExportFields(3)">添加全部</HLink>
          </el-space>
          <div style="max-height: 220px; overflow-y: auto; width: 100%; padding-top: 6px">
            <el-space wrap :size="10">
              <div
                :key="column.value"
                v-for="column in orderSettlementField"
                @mouseenter="() => (column.showAdd = true)"
                @mouseleave="() => (column.showAdd = false)"
                class="add-field-item"
                @click="addOrderSettlementField(column)"
              >
                <div class="add-field-item-text">{{ column.name }}</div>
                <div class="add-field-item-btn">+</div>
              </div>
            </el-space>
          </div>
        </div>
      </div>
      <template #footerRight>
        <HButton type="success" isModal @click="handleSaveAndExportField">保存并导出</HButton>
        <HButton type="primary" isModal @click="onSaveExportField">保存</HButton>
        <HButton isModal @click="onClose">取消</HButton>
      </template>
    </HModal>
  </div>
</template>

<style scoped lang="scss">
  @import './FieldExport.scss';
</style>
